import io from 'socket.io-client'
import ip from './ip.js'
const USER = {
    userid:null,
    username:null,
    nick:null,
    openid:null,
    socket:null,
    mch_id:0,
    mch_name:'',
    usertype:null,
    userinfo:{},
    status:0,
    playerArr:[],
    listened:'',
    init:function(_user){

        this.socket = io.connect("ws://" + ip)
        console.log('初始化init')

        // 监听用户加入
        // this.socket.on('joined',(nick)=>{
        //     console.log("236:"+nick)
        //     USER.playerArr.push(nick)
        // })

        this.userinfo.openid = _user.openid
        this.userinfo.nick = _user.nick
        this.userinfo.username = _user.username
        this.userinfo.mch_id = _user.mch_id
        this.userinfo.mch_name = _user.mch_name
        this.userinfo.head = _user.head
        this.userinfo.usertype = _user.usertype

        // 初始化读取cookie,如果为空则第一次扫
        var login_info = this.getCookie('login_info')
        var login_status = this.getCookie('login_status')

        if(!login_info){
            this.setCookie('login_info',this.userinfo.mch_id+","+this.userinfo.mch_name)
            this.setCookie('login_status',0)
            login_info = this.userinfo.mch_id+","+this.userinfo.mch_name
        }

        this.userinfo.mch_id = login_info.split(",")[0]
        this.userinfo.mch_name = login_info.split(",")[1]
        this.userinfo.status = login_status

    },
    start:function(){
      //   this.socket.emit('login',{
		  //   nick:this.userinfo.nick,
      //   mch_id:this.userinfo.mch_id,
      //   mch_name:this.userinfo.mch_name,
      //   usertype:this.userinfo.usertype
		  // })
    },
    disconnect:function(user){

    },
    setCookie: function (key, value, times) {
        // 设置过期原则
        if (!value) {
          localStorage.removeItem(key)
        } else {
          var Times = times || 8; // 默认保留6小时
          var exp = new Date();
          localStorage[key] = JSON.stringify({
            value,
            expires: exp.getTime() + Times * 60 * 60 * 1000
          })
        }
      },
      getCookie: function (name) {
        try {
          let o = JSON.parse(localStorage[name])
          if (!o || o.expires < Date.now()) {
            return null
          } else {
            return o.value
          }
        } catch (e) {
            // 兼容其他localstorage 
        //   console.log(e)
          return localStorage[name]
        } finally {
        }
      }

}

export default USER